package com.ruoyi.framework.satoken;

import cn.dev33.satoken.dao.SaTokenDao;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.strategy.SaStrategy;
import cn.dev33.satoken.util.SaFoxUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.domain.entity.SaTokenDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class SaTokenDaoImpl implements SaTokenDao {


    @Override
    public String get(String s) {
        String s1 = CacheUtils.get(CacheConstants.SYSTEM_SATOEKN, s, String.class);
        if (StringUtils.isNotBlank(s1)) {
            SaTokenDO saTokenDO = JSONObject.parseObject(s1, SaTokenDO.class);
            long between = DateUtil.between(new Date(), saTokenDO.getCreateTime(), DateUnit.SECOND);
            if (saTokenDO.getTimeOut() - between > 0) {
                this.updateTimeout(s, saTokenDO.getTimeOut() - between);
                return saTokenDO.getValue();
            } else {
                this.delete(s);
                return null;
            }

        }
        return null;
    }

    @Override
    public void set(String s, String s1, long l) {
        SaTokenDO saTokenDO = new SaTokenDO();
        saTokenDO.setTokenKey(s);
        saTokenDO.setValue(s1);
        saTokenDO.setTimeOut(l);
        saTokenDO.setCreateTime(new Date());
        CacheUtils.put(CacheConstants.SYSTEM_SATOEKN, s, JSONObject.toJSONString(saTokenDO));
    }

    @Override
    public void update(String s, String s1) {
        SaTokenDO saTokenDO = CacheUtils.get(CacheConstants.SYSTEM_SATOEKN, s, SaTokenDO.class);
        saTokenDO.setValue(s1);
        CacheUtils.put(CacheConstants.SYSTEM_SATOEKN, s, JSONObject.toJSONString(saTokenDO));
    }

    @Override
    public void delete(String s) {
        CacheUtils.remove(CacheConstants.SYSTEM_SATOEKN, s);
    }

    @Override
    public long getTimeout(String s) {
        String s1 = CacheUtils.get(CacheConstants.SYSTEM_SATOEKN, s, String.class);
        if (StringUtils.isNotBlank(s1)) {
            SaTokenDO saTokenDO = JSONObject.parseObject(s1, SaTokenDO.class);
            long between = DateUtil.between(new Date(), saTokenDO.getCreateTime(), DateUnit.SECOND);
            return saTokenDO.getTimeOut() - between;
        }
        return -1;
    }

    @Override
    public void updateTimeout(String s, long l) {
        String s1 = CacheUtils.get(CacheConstants.SYSTEM_SATOEKN, s, String.class);
        if (StringUtils.isNotBlank(s1)) {
            SaTokenDO saTokenDO = JSONObject.parseObject(s1, SaTokenDO.class);
            saTokenDO.setTimeOut(l);
            saTokenDO.setCreateTime(new Date());
            CacheUtils.put(CacheConstants.SYSTEM_SATOEKN, s, JSONObject.toJSONString(saTokenDO));
        }

    }

    @Override
    public Object getObject(String s) {
        String s1 = CacheUtils.get(CacheConstants.SYSTEM_SATOEKN, s, String.class);
        if (StringUtils.isNotBlank(s1)) {
            SaTokenDO saTokenDO = JSONObject.parseObject(s1, SaTokenDO.class);
            long between = DateUtil.between(new Date(), saTokenDO.getCreateTime(), DateUnit.SECOND);
            if (saTokenDO.getTimeOut() - between > 0) {
                this.updateObjectTimeout(s, saTokenDO.getTimeOut() - between);
                return JSONObject.parseObject(saTokenDO.getValue(), SaSession.class);
            } else {
                this.deleteObject(s);
                return null;
            }
        }
        return null;
    }

    @Override
    public <T> T getObject(String s, Class<T> aClass) {
        String s1 = CacheUtils.get(CacheConstants.SYSTEM_SATOEKN, s, String.class);
        if (StringUtils.isNotBlank(s1)) {
            SaTokenDO saTokenDO = JSONObject.parseObject(s1, SaTokenDO.class);
            long between = DateUtil.between(new Date(), saTokenDO.getCreateTime(), DateUnit.SECOND);
            if (saTokenDO.getTimeOut() - between > 0) {
                this.updateObjectTimeout(s, saTokenDO.getTimeOut() - between);
                return JSONObject.parseObject(saTokenDO.getValue(), aClass);
            } else {
                this.deleteObject(s);
                return null;
            }
        }
        return null;
    }

    @Override
    public void setObject(String s, Object o, long l) {
        SaTokenDO saTokenDO = new SaTokenDO();
        saTokenDO.setTokenKey(s);
        saTokenDO.setValue(JSONObject.toJSONString(o));
        saTokenDO.setTimeOut(l);
        saTokenDO.setCreateTime(new Date());
        CacheUtils.put(CacheConstants.SYSTEM_SATOEKN, s, JSONObject.toJSONString(saTokenDO));
    }

    @Override
    public void updateObject(String s, Object o) {
        String s1 = CacheUtils.get(CacheConstants.SYSTEM_SATOEKN, s, String.class);
        if (StringUtils.isNotBlank(s1)) {
            SaTokenDO saTokenDO = JSONObject.parseObject(s1, SaTokenDO.class);
            saTokenDO.setTokenKey(s);
            saTokenDO.setValue(JSONObject.toJSONString(o));
            saTokenDO.setCreateTime(new Date());
            CacheUtils.put(CacheConstants.SYSTEM_SATOEKN, s, JSONObject.toJSONString(saTokenDO));
        } else {
            SaTokenDO saTokenDO = new SaTokenDO();
            saTokenDO.setTokenKey(s);
            saTokenDO.setValue(JSONObject.toJSONString(o));
            saTokenDO.setCreateTime(new Date());
            CacheUtils.put(CacheConstants.SYSTEM_SATOEKN, s, JSONObject.toJSONString(saTokenDO));
        }

    }

    @Override
    public void deleteObject(String s) {
        CacheUtils.remove(CacheConstants.SYSTEM_SATOEKN, s);
    }

    @Override
    public long getObjectTimeout(String s) {
        String s1 = CacheUtils.get(CacheConstants.SYSTEM_SATOEKN, s, String.class);
        if (StringUtils.isNotBlank(s1)) {
            SaTokenDO saTokenDO = JSONObject.parseObject(s1, SaTokenDO.class);
            long between = DateUtil.between(new Date(), saTokenDO.getCreateTime(), DateUnit.SECOND);
            return saTokenDO.getTimeOut() - between;
        }
        return -1;
    }

    @Override
    public void updateObjectTimeout(String s, long l) {
//        log.info("---------- [SaTokenDaoImpl] 更新对象超时时间 updateObjectTimeout,tokenKey:{},timeout:{}", s, l);
        String s1 = CacheUtils.get(CacheConstants.SYSTEM_SATOEKN, s, String.class);
        if (StringUtils.isNotBlank(s1)) {
            SaTokenDO saTokenDO = JSONObject.parseObject(s1, SaTokenDO.class);
            saTokenDO.setTimeOut(l);
            saTokenDO.setCreateTime(new Date());
            CacheUtils.put(CacheConstants.SYSTEM_SATOEKN, s, JSONObject.toJSONString(saTokenDO));
        }

    }


    @Override
    public SaSession getSession(String sessionId) {
        return (SaSession) this.getObject(sessionId, SaStrategy.instance.sessionClassType);
    }

    @Override
    public void setSession(SaSession saSession, long timeout) {
        this.setObject(saSession.getId(), saSession, timeout);
    }

    @Override
    public void updateSession(SaSession saSession) {
        this.updateObject(saSession.getId(), saSession);
    }

    @Override
    public void deleteSession(String sessionId) {
        this.deleteObject(sessionId);
    }

    @Override
    public long getSessionTimeout(String sessionId) {
        return this.getObjectTimeout(sessionId);
    }

    @Override
    public void updateSessionTimeout(String sessionId, long timeout) {
        this.updateObjectTimeout(sessionId, timeout);
    }

    /**
     * prefix – 前缀 keyword – 关键字 start – 开始处索引 size – 获取数量 (-1代表从 start 处一直取到末尾) sortType – 排序类型（true=正序，false=反序）
     * Returns:
     * 查询到的数据集合
     *
     * @param prefix   前缀
     * @param keyword  关键字
     * @param start    开始处索引
     * @param size     获取数量  (-1代表从 start 处一直取到末尾)
     * @param sortType 排序类型（true=正序，false=反序）
     * @return
     */
    @Override
    public List<String> searchData(String prefix, String keyword, int start, int size, boolean sortType) {
        return SaFoxUtil.searchList(CacheUtils.getkeys(CacheConstants.SYSTEM_SATOEKN), prefix, keyword, start, size, sortType);
    }
}
